package com.bw.seckill.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.ResponseResult;
import com.bw.common.auth.JwtUtils;
import com.bw.common.auth.RsaUtils;
import com.bw.common.auth.UserInfo;
import com.bw.seckill.entity.TbSeller;
import com.bw.seckill.entity.TbUser;
import com.bw.seckill.service.ITbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xingjinning
 * @since 2020-07-14
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class TbUserController {

    @Autowired
    private ITbUserService userService;
    @Value("${keyPath}")
    private String keyPath;

    @PostMapping("login")
    public ResponseResult login(@RequestBody TbUser tbUser){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            Map map = new HashMap<>();
            map.put("loginName",tbUser.getLoginName());
            map.put("pwd",tbUser.getPwd());
            queryWrapper.allEq(map);
            List<TbUser> list = userService.list();
            if(list.size()>0){
                TbUser tbUser1 = list.get(0);
                PrivateKey privateKey = RsaUtils.getPrivateKey(keyPath + "rsa.pri");
                UserInfo userInfo = new UserInfo();
                userInfo.setId(tbUser1.getId());
                userInfo.setUsername(tbUser1.getFullName());
                String token = JwtUtils.generateToken(userInfo, privateKey, 60);
                Map mapinfo = new HashMap();
                mapinfo.put("user",tbUser1);
                mapinfo.put("token",token);
                result.setMessage("登陆成功");
                result.setResult(mapinfo);
            }else{
                result.setMessage("用户名或密码错误");
                result.setSuccess(false);
            }
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("登录异常"+e.toString());
        }
        return result;
    }

}
